﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewResourceDevice : Form
    {
        public fmNewResourceDevice()
        {
            InitializeComponent();
        }

        private void fmNewResourceDevice_Load(object sender, EventArgs e)
        {
            
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {

            DataTable dtSite = SiteBindingSource.DataSource as DataTable;


            if (dtSite == null || !dtSite.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            var drSite = dtSite.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");

            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            if (string.IsNullOrWhiteSpace(txtBindDate.Text))
            {
                MessageBox.Show("绑定时间不可为空！");
                return;
            }
            string format = "yyyyMMdd";
            if (!DateTime.TryParseExact(txtBindDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime BindDate))
            {
                MessageBox.Show("绑定时间的时间格式错误！");
                return;
            }

            var drs = dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True");
            var ids = drs.Select(x => x["ID"].ToString()).ToList();

            var dtResourceObject = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,device_key FROM custom_resource_object_device WHERE custom_resource_object_id={MySQLHelper.ConvertGuidToSql(drSite["id"].ToString())} and deleted = 0 and device_key IN ({MySQLHelper.ConvertListToStr(ids)})");
            if (dtResourceObject != null && dtResourceObject.Rows.Count > 0)
            {
                MessageBox.Show($@"已存在设备对象{string.Join(",", dtResourceObject.AsEnumerable().Select(x => x["device_key"].ToString()))}！");
                return;
            }


            List<string> sqlList = new List<string>();
            //插入数据
            foreach (var item in dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True"))
            {
                sqlList.Add($@"insert into custom_resource_object_device (custom_resource_object_id,device_key,binding_time,create_time,update_time)VALUES ({MySQLHelper.ConvertGuidToSql(drSite["id"].ToString())},{MySQLHelper.ConvertGuidToSql(item["ID"].ToString())},'{BindDate}',NOW(),NOW())");
            }

            if (await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, sqlList))
            {
                MessageBox.Show("新建资源对象设备成功");
            }
            else
            {
                MessageBox.Show("新建资源对象设备失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT custom_resource_object.id,custom_resource_object.factory_station_id,custom_resource_object.fname,custom_resource_type.type_name,custom_resource_object.parent_factory_station_id,custom_resource_object.custom_no FROM custom_resource_object LEFT JOIN custom_resource_type ON custom_resource_object.custom_resource_type_id = custom_resource_type.id WHERE custom_resource_object.fname LIKE '%{txtSiteName.Text}%' ORDER BY custom_resource_object.fname,custom_resource_type.range_type,custom_resource_type.id ");
            if (dtA == null || dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;

            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            SiteBindingSource.DataSource = dtA;
            dgSite.DataSource = SiteBindingSource;

            dgSite.Columns["id"].HeaderText = "ID";
            dgSite.Columns["factory_station_id"].HeaderText = "站点ID";
            dgSite.Columns["fname"].HeaderText = "企业或园区名称";
            dgSite.Columns["type_name"].HeaderText = "资源类型";
            dgSite.Columns["parent_factory_station_id"].HeaderText = "上级园区ID";
            dgSite.Columns["custom_no"].HeaderText = "户号";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dgSite_CellContentClick;


            if (!dgDevice.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn();
                checkBoxColumn2.HeaderText = "选中";
                checkBoxColumn2.Name = "IsSelected";
                checkBoxColumn2.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgDevice.Columns.Add(checkBoxColumn2);
            }

            // 设置不允许新增行
            dgDevice.AllowUserToAddRows = false;

            dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

            dgDevice.ContextMenuStrip = contextMenuStrip1;
        }

        private async void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgSite.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgSite.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = SiteBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }

                    var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID from dev_powersystemresource where PATHID like '%\\\\{drv["factory_station_id"]}%' AND CLASSNAME = 'Bay' order by PATHID;");
                    if (dtA.Rows.Count == 0)
                    {
                        MessageBox.Show("没有查询到相关数据");
                        return;
                    }
                    // 为DataTable添加对应的列
                    dtA.Columns.Add("IsSelected", typeof(bool));
                    dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                    DeviceBindingSource.DataSource = dtA;
                    dgDevice.DataSource = DeviceBindingSource;

                    dgDevice.Columns["ID"].HeaderText = "ID";
                    dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
                    dgDevice.Columns["NAME"].HeaderText = "名称";
                    dgDevice.Columns["PATHID"].HeaderText = "路径";
                    dgDevice.AutoResizeColumns();
                    lbCount.Text = dtA.Rows.Count.ToString();
                }
            }

        }


        private void txtEndDate_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void tsmAllSelect_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = true;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

        private void tsmAllCancel_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = false;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }



        private void txtParentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                e.Handled = true;
            }
        }
    }
}
